package com.sc.nft.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sc.nft.dao.MallDrawActivityBaseDao;
import com.sc.nft.dao.MallDrawActivityPrizePoolDao;
import com.sc.nft.dao.MallDrawActivityPrizePoolDetailDao;
import com.sc.nft.dao.MallDrawActivityPropDao;
import com.sc.nft.entity.MallDrawActivityBase;
import com.sc.nft.entity.MallDrawActivityPrizePool;
import com.sc.nft.entity.MallDrawActivityPrizePoolDetail;
import com.sc.nft.entity.MallDrawActivityProp;
import com.sc.nft.entity.dto.draw.activity.MallDrawActivityDTO;
import com.sc.nft.entity.dto.draw.activity.MallDrawActivityPrizePoolDTO;
import com.sc.nft.entity.dto.draw.activity.MallDrawActivityPrizePoolDetailDTO;
import com.sc.nft.entity.vo.draw.activity.MallDrawActivityBaseVO;
import com.sc.nft.enums.draw.activity.DrawActivityStateEnum;
import com.sc.nft.enums.draw.activity.PropTypeEnum;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.mapstruct.MallDrawActivityMapStruct;
import com.sc.nft.service.MallDrawActivityBaseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Service
public class MallDrawActivityBaseServiceImpl implements MallDrawActivityBaseService {

    private final MallDrawActivityBaseDao mallDrawActivityBaseDao;

    private final MallDrawActivityPrizePoolDao mallDrawActivityPrizePoolDao;

    private final MallDrawActivityPropDao mallDrawActivityPropDao;

    private final MallDrawActivityPrizePoolDetailDao mallDrawActivityPrizePoolDetailDao;

    private static final String INTEGRAL_IMG = "https://cdn.gometa.com.cn/scnft/h5_default/DDD5AA3D5D4A5307";
    private static final String NONE_IMG = "https://cdn.gometa.com.cn/scnft/h5_default/09985361BDB58CBE";


    @Override
    public Page<MallDrawActivityBaseVO> page(Page toMp) {
        Page<MallDrawActivityBaseVO> mallDrawActivityBaseVOPage = MallDrawActivityMapStruct.INSTANCE.mallDrawActivityBase2VOPage(mallDrawActivityBaseDao.page(toMp, new LambdaQueryWrapper<MallDrawActivityBase>().orderByDesc(MallDrawActivityBase::getId)));
        // 获取当前时间
        Date now = new Date();
        for (MallDrawActivityBaseVO record : mallDrawActivityBaseVOPage.getRecords()) {
            record.setState(getState(record.getStartTime(), record.getEndTime()).getCode());
        }
        return mallDrawActivityBaseVOPage;
    }

    public DrawActivityStateEnum getState(Date startTime, Date endTime) {
        Date now = new Date();
        if (now.before(startTime)) {
            return DrawActivityStateEnum.PENDING; // 待开始
        } else if (now.after(endTime)) {
            return DrawActivityStateEnum.ENDED; // 已结束
        } else {
            return DrawActivityStateEnum.ONGOING; // 进行中
        }
    }


    @Override
    public MallDrawActivityBase getById(Long id) {
        return mallDrawActivityBaseDao.getById(id);
    }

    @Override
    public List<MallDrawActivityBase> listByIds(List<Long> id) {
        return mallDrawActivityBaseDao.listByIds(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean save(MallDrawActivityDTO mallDrawActivityDTO) {
        //保存活动表
        MallDrawActivityBase mallDrawActivityBase = MallDrawActivityMapStruct.INSTANCE.mallDrawActivityDTO2DO(mallDrawActivityDTO);
        if (mallDrawActivityDTO.getId() == null) {
            Assert.isTrue(!mallDrawActivityDTO.getStartTime().before(new Date()), () -> new GlobalRunTimeException("开始时间不能早于当前时间！"));

            Assert.isTrue(!mallDrawActivityDTO.getEndTime().before(mallDrawActivityDTO.getStartTime()), () -> new GlobalRunTimeException("结束时间不能早于开始时间！"));
            mallDrawActivityBase.setEnabled(false);
        }
        mallDrawActivityBaseDao.saveOrUpdate(mallDrawActivityBase);
        if (mallDrawActivityDTO.getStartTime() != null && mallDrawActivityDTO.getEndTime() != null) {
            DrawActivityStateEnum drawActivityStateEnum = this.getState(mallDrawActivityDTO.getStartTime(), mallDrawActivityDTO.getEndTime());
            //如果活动是进行中，不执行保存道具和保存奖池的逻辑
            if (drawActivityStateEnum == DrawActivityStateEnum.ONGOING) {
                return true;
            }
        }

        if (!CollectionUtils.isEmpty(mallDrawActivityDTO.getMallDrawActivityPropRequestList())) {
            List<MallDrawActivityProp> mallDrawActivityPropList = MallDrawActivityMapStruct.INSTANCE.mallDrawActivityPropDTO2DO(mallDrawActivityDTO.getMallDrawActivityPropRequestList());
            //填充活动id
            for (MallDrawActivityProp mallDrawActivityProp : mallDrawActivityPropList) {
                mallDrawActivityProp.setActivityId(mallDrawActivityBase.getId());
            }
            if (mallDrawActivityDTO.getId() != null) {
                mallDrawActivityPropDao.removeByActivityId(mallDrawActivityDTO.getId());
            }
            //保存活动抽奖道具
            mallDrawActivityPropDao.saveOrUpdateBatch(mallDrawActivityPropList);
        }

        if (!CollectionUtils.isEmpty(mallDrawActivityDTO.getMallDrawActivityPrizePoolList())) {
            if (mallDrawActivityDTO.getId() != null) {
                mallDrawActivityPrizePoolDao.removeByActivityId(mallDrawActivityBase.getId());
            }
            Integer poolIndex = 1;
            for (MallDrawActivityPrizePoolDTO mallDrawActivityPrizePoolDTO : mallDrawActivityDTO.getMallDrawActivityPrizePoolList()) {
                MallDrawActivityPrizePool mallDrawActivityPrizePool = MallDrawActivityMapStruct.INSTANCE.mallDrawActivityPrizePoolDTO2DO(mallDrawActivityPrizePoolDTO);
                mallDrawActivityPrizePool.setActivityId(mallDrawActivityBase.getId());
                mallDrawActivityPrizePool.setPoolIndex(poolIndex);
                //保存奖池表
                mallDrawActivityPrizePoolDao.saveOrUpdate(mallDrawActivityPrizePool);
                if (!CollectionUtils.isEmpty(mallDrawActivityDTO.getMallDrawActivityPrizePoolList())) {
                    List<MallDrawActivityPrizePoolDetail> drawActivityPrizePoolDetailList = new ArrayList<>();
                    Integer detailIndex = 1;
                    for (MallDrawActivityPrizePoolDetailDTO mallDrawActivityPrizePoolDetailDTO : mallDrawActivityPrizePoolDTO.getMallDrawActivityPrizePoolDetailList()) {
                        MallDrawActivityPrizePoolDetail mallDrawActivityPrizePoolDetail = MallDrawActivityMapStruct.INSTANCE.mallDrawActivityPrizePoolDetailDTO2DO(mallDrawActivityPrizePoolDetailDTO);
                        mallDrawActivityPrizePoolDetail.setPoolId(mallDrawActivityPrizePool.getId());
                        mallDrawActivityPrizePoolDetail.setDetailIndex(detailIndex);
                        Integer totalPrizeCount = 0;
                        if (mallDrawActivityPrizePoolDetail.getPropType() != PropTypeEnum.NONE) {
                            totalPrizeCount = mallDrawActivityPrizePoolDetail.getTotalPrizeCount() * mallDrawActivityPrizePoolDetail.getPrizeCount();
                        }
                        mallDrawActivityPrizePoolDetail.setTotalPrizeCount(totalPrizeCount);
                        if (mallDrawActivityPrizePoolDetail.getPropType() == PropTypeEnum.INTEGRAL) {
                            mallDrawActivityPrizePoolDetail.setPropName("星球碎片");
                            mallDrawActivityPrizePoolDetail.setPropImg(INTEGRAL_IMG);
                        } else if (mallDrawActivityPrizePoolDetail.getPropType() == PropTypeEnum.NONE) {
                            mallDrawActivityPrizePoolDetail.setPropName("感谢参与");
                            mallDrawActivityPrizePoolDetail.setPropImg(NONE_IMG);
                        }
                        if (mallDrawActivityPrizePoolDetail.getId() == null) {
                            mallDrawActivityPrizePoolDetail.setRemainingPrizeCount(totalPrizeCount);
                        }
                        if (mallDrawActivityPrizePoolDetailDTO.getId() != null) {
                            mallDrawActivityPrizePoolDetailDao.removeByPrizePoolId(mallDrawActivityPrizePoolDTO.getId());
                        }
                        drawActivityPrizePoolDetailList.add(mallDrawActivityPrizePoolDetail);
                        detailIndex++;
                    }

                    //保存奖池明细表
                    mallDrawActivityPrizePoolDetailDao.saveOrUpdateBatch(drawActivityPrizePoolDetailList);
                }
                poolIndex++;
            }
        }
        return true;
    }

    @Override
    public Page<MallDrawActivityBase> listEnabledActivity(Page page) {
        return mallDrawActivityBaseDao.listEnabledActivity(page);
    }

    @Override
    public MallDrawActivityDTO get(Long id) {
        MallDrawActivityBase mallDrawActivityBase = mallDrawActivityBaseDao.getById(id);
        if (mallDrawActivityBase == null) {
            return null;
        }
        MallDrawActivityDTO mallDrawActivityDTO = MallDrawActivityMapStruct.INSTANCE.mallDrawActivityBase2DTO(mallDrawActivityBase);
        // 获取当前时间
        Date now = new Date();
        Date startTime = mallDrawActivityBase.getStartTime();
        Date endTime = mallDrawActivityBase.getEndTime();
        if (now.before(startTime)) {
            mallDrawActivityDTO.setState(DrawActivityStateEnum.PENDING.getCode()); // 待开始
        } else if (now.after(endTime)) {
            mallDrawActivityDTO.setState(DrawActivityStateEnum.ENDED.getCode()); // 已结束
        } else {
            mallDrawActivityDTO.setState(DrawActivityStateEnum.ONGOING.getCode()); // 进行中
        }
        LambdaQueryWrapper<MallDrawActivityProp> drawActivityPropWrapper = new LambdaQueryWrapper<>();
        drawActivityPropWrapper.eq(MallDrawActivityProp::getActivityId, mallDrawActivityBase.getId());
        List<MallDrawActivityProp> mallDrawActivityPropList = mallDrawActivityPropDao.list(drawActivityPropWrapper);
        //填充抽奖道具
        mallDrawActivityDTO.setMallDrawActivityPropRequestList(MallDrawActivityMapStruct.INSTANCE.mallDrawActivityPropList2DTO(mallDrawActivityPropList));
        //填充奖池
        LambdaQueryWrapper<MallDrawActivityPrizePool> drawActivityPrizePoolWrapper = new LambdaQueryWrapper<>();
        drawActivityPrizePoolWrapper.eq(MallDrawActivityPrizePool::getActivityId, mallDrawActivityBase.getId());
        List<MallDrawActivityPrizePool> mallDrawActivityPrizePoolList = mallDrawActivityPrizePoolDao.list(drawActivityPrizePoolWrapper);
        List<MallDrawActivityPrizePoolDTO> mallDrawActivityPrizePoolDTOList = new ArrayList<>();
        for (MallDrawActivityPrizePool mallDrawActivityPrizePool : mallDrawActivityPrizePoolList) {
            MallDrawActivityPrizePoolDTO mallDrawActivityPrizePoolDTO = MallDrawActivityMapStruct.INSTANCE.mallDrawActivityPrizePool2DTO(mallDrawActivityPrizePool);
            LambdaQueryWrapper<MallDrawActivityPrizePoolDetail> drawActivityPrizePoolDetailWrapper = new LambdaQueryWrapper<>();
            drawActivityPrizePoolDetailWrapper.eq(MallDrawActivityPrizePoolDetail::getPoolId, mallDrawActivityPrizePool.getId());
            List<MallDrawActivityPrizePoolDetail> mallDrawActivityPrizePoolDetailList = mallDrawActivityPrizePoolDetailDao.list(drawActivityPrizePoolDetailWrapper);
            List<MallDrawActivityPrizePoolDetailDTO> mallDrawActivityPrizePoolDetailDTOList = MallDrawActivityMapStruct.INSTANCE.mallDrawActivityPrizePoolDetail2DTO(mallDrawActivityPrizePoolDetailList);
            for (MallDrawActivityPrizePoolDetailDTO mallDrawActivityPrizePoolDetailDTO : mallDrawActivityPrizePoolDetailDTOList) {
                if (mallDrawActivityPrizePoolDetailDTO.getPrizeCount() != 0) {
                    mallDrawActivityPrizePoolDetailDTO.setTotalPrizeCount(mallDrawActivityPrizePoolDetailDTO.getTotalPrizeCount() / mallDrawActivityPrizePoolDetailDTO.getPrizeCount());
                    mallDrawActivityPrizePoolDetailDTO.setRemainingPrizeCount(mallDrawActivityPrizePoolDetailDTO.getRemainingPrizeCount() / mallDrawActivityPrizePoolDetailDTO.getPrizeCount());
                }
            }
            mallDrawActivityPrizePoolDTO.setMallDrawActivityPrizePoolDetailList(mallDrawActivityPrizePoolDetailDTOList);
            mallDrawActivityPrizePoolDTOList.add(mallDrawActivityPrizePoolDTO);
        }
        mallDrawActivityDTO.setMallDrawActivityPrizePoolList(mallDrawActivityPrizePoolDTOList);
        return mallDrawActivityDTO;
    }


}
